package com.isoft.util;

import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Unmarshaller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.StringReader;

@Component
public class XmlParserUtil {
    private static final Logger logger = LoggerFactory.getLogger(XmlParserUtil.class);

    public <T> T parseXml(String xmlContent, Class<T> clazz) throws Exception {
        try {
            // 1. 预处理XML内容
            String processedXml = preprocessXml(xmlContent);

            // 2. 记录XML前500字符用于调试
            int previewLength = Math.min(processedXml.length(), 500);
            String preview = processedXml.substring(0, previewLength);
            logger.debug("XML content to parse (first {} chars): {}", previewLength, preview);

            // 3. 使用JAXB解析XML
            JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

            // 4. 创建StringReader
            StringReader reader = new StringReader(processedXml);

            // 5. 解析XML
            @SuppressWarnings("unchecked")
            T result = (T) unmarshaller.unmarshal(reader);

            // 6. 记录解析结果
            logger.debug("Successfully parsed XML into {}", clazz.getSimpleName());
            logger.debug("Parsed entity details: {}", result);

            return result;
        } catch (JAXBException e) {
            logger.error("XML parsing failed due to: {}", e.getMessage());
            logger.error("Detailed error:", e);
            throw new Exception("XML parsing error: " + e.getMessage(), e);
        } catch (Exception e) {
            logger.error("Unexpected error during XML parsing: {}", e.getMessage());
            throw e;
        }
    }

    private String preprocessXml(String xml) {
        // 1. 移除BOM头
        if (xml.startsWith("\uFEFF")) {
            xml = xml.substring(1);
        }

        // 2. 确保XML声明存在
        if (!xml.startsWith("<?xml")) {
            xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + xml;
        }

        // 3. 处理自闭合标签
        xml = xml.replaceAll("<RCVR\\s*/>", "<RCVR></RCVR>");

        return xml.trim();
    }
}